Completed
Push — master ( c2963c...bfce84 )
by Felipe
36s
created

_.extend.route   B

Complexity

Conditions 4
Paths 8

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
c 1
b 0
f 0
nc 8
nop 3
dl 0
loc 23
rs 8.7972

1 Function

Rating   Name   Duplication   Size   Complexity  
A 0 9 2
1
import $ from 'jquery';
0 ignored issues
show
introduced by
Definition for rule 'keyword-spacing' was not found
Loading history...
2
import _ from 'underscore';
3
import {
4
  Backbone
5
} from './core.js';
6
import {
7
  Events
8
} from './events.js';
9
10
// Backbone.Router
11
// ---------------
12
13
// Routers map faux-URLs to actions, and fire events when routes are
14
// matched. Creating a new one sets its `routes` hash, if not set statically.
15
var Router = function (options) {
16
  options = options || {};
17
  this.preinitialize.apply(this, arguments);
18
  if (options.routes) {
19
    this.routes = options.routes;
20
  }
21
  this._bindRoutes();
22
  this.initialize.apply(this, arguments);
23
};
24
25
// Cached regular expressions for matching named param parts and splatted
26
// parts of route strings.
27
var optionalParam = /\((.*?)\)/g;
28
var namedParam = /(\(\?)?:\w+/g;
29
var splatParam = /\*\w+/g;
30
var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g;
31
32
// Set up all inheritable **Backbone.Router** properties and methods.
33
_.extend(Router.prototype, Events, {
34
35
  // preinitialize is an empty function by default. You can override it with a function
36
  // or object.  preinitialize will run before any instantiation logic is run in the Router.
37
  preinitialize: function () {},
38
39
  // Initialize is an empty function by default. Override it with your own
40
  // initialization logic.
41
  initialize: function () {},
42
43
  // Manually bind a single named route to a callback. For example:
44
  //
45
  //     this.route('search/:query/p:num', 'search', function(query, num) {
46
  //       ...
47
  //     });
48
  //
49
  route: function (route, name, callback) {
50
    if (!_.isRegExp(route)) {
51
      route = this._routeToRegExp(route);
52
    }
53
    if (_.isFunction(name)) {
54
      callback = name;
55
      name = '';
56
    }
57
    if (!callback) {
58
      callback = this[name];
59
    }
60
    var router = this;
0 ignored issues
show
introduced by
Unexpected alias 'router' for 'this'.
Loading history...
61
    Backbone.history.route(route, function (fragment) {
62
      var args = router._extractParameters(route, fragment);
63
      if (router.execute(callback, args, name) !== false) {
64
        router.trigger.apply(router, ['route:' + name].concat(
65
          args));
66
        router.trigger('route', name, args);
67
        Backbone.history.trigger('route', router, name, args);
68
      }
69
    });
70
    return this;
71
  },
72
73
  // Execute a route handler with the provided parameters.  This is an
74
  // excellent place to do pre-route setup or post-route cleanup.
75
  execute: function (callback, args, name) {
0 ignored issues
show
Unused Code introduced by
The parameter name is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
76
    if (callback) {
77
      callback.apply(this, args);
78
    }
79
  },
80
81
  // Simple proxy to `Backbone.history` to save a fragment into the history.
82
  navigate: function (fragment, options) {
83
    Backbone.history.navigate(fragment, options);
84
    return this;
85
  },
86
87
  // Bind all defined routes to `Backbone.history`. We have to reverse the
88
  // order of the routes here to support behavior where the most general
89
  // routes can be defined at the bottom of the route map.
90
  _bindRoutes: function () {
91
    if (!this.routes) return;
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
introduced by
Expected { after 'if' condition.
Loading history...
92
    this.routes = _.result(this, 'routes');
93
    var route, routes = _.keys(this.routes);
94
    while ((route = routes.pop()) != null) {
0 ignored issues
show
introduced by
Use ‘===’ to compare with ‘null’.
Loading history...
Bug Best Practice introduced by
Apart from some edge-cases, it is generally advisable to use the strict comparison !== instead of !=.

The loose comparison such as == or != might produce some weird results for some values, unless you explicitly want to have this behavior here, better use the strict alternative.

Learn more about loose comparison in Javascript.

Loading history...
95
      this.route(route, this.routes[route]);
96
    }
97
  },
98
99
  // Convert a route string into a regular expression, suitable for matching
100
  // against the current location hash.
101
  _routeToRegExp: function (route) {
102
    route = route.replace(escapeRegExp, '\\$&')
103
      .replace(optionalParam, '(?:$1)?')
104
      .replace(namedParam, function (match, optional) {
105
        return optional ? match : '([^/?]+)';
106
      })
107
      .replace(splatParam, '([^?]*?)');
108
    return new RegExp('^' + route + '(?:\\?([\\s\\S]*))?$');
109
  },
110
111
  // Given a route, and a URL fragment that it matches, return the array of
112
  // extracted decoded parameters. Empty or unmatched parameters will be
113
  // treated as `null` to normalize cross-browser behavior.
114
  _extractParameters: function (route, fragment) {
115
    var params = route.exec(fragment).slice(1);
116
    return _.map(params, function (param, i) {
117
      // Don't decode the search params.
118
      if (i === params.length - 1) {
119
        return param || null;
120
      }
121
      return param ? decodeURIComponent(param) : null;
122
    });
123
  }
124
125
});
126
127
export {
128
  Router
129
};
130